package com.tianci.appstore.ui.dialog;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.utils.SkyConstants;
import com.tianci.appstore.utils.SystemUtils;

public class SpeedUpDialog extends CommonDialog {
    private FrameLayout speedLayout;
    private ImageView greenLightImage;
    private TextView memoryPercentText;
    private TextView tip1Text, tip2Text, tip3Text;
    private ImageView tip1Image, tip2Image, tip3Image;
    private TextView speedingTipText;

    private int speed = 15;
    private int crtShowPercent = 0;
    private int originalPercent = 0;
    private int brightColor;
    private int darkColor;
    private int numTextSize = SkyConstants.Dpi(80);
    private int percentTextSize = SkyConstants.Dpi(30);
    private Animation rotateAnim = null;

    public SpeedUpDialog(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        iconImage.setBackgroundDrawable(SkinManager.getResDrawable(R.drawable.icon_speed));
        mTitleView.setText(R.string.main_speed);
        initSpeedUpLayout();
    }

    private void initSpeedUpLayout() {
        speedLayout = new FrameLayout(mContext);
        speedLayout.setPadding(0, 0, 0, SkyConstants.Div(40));
        mainLayout.addView(speedLayout, new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        ImageView shadowImage = new ImageView(mContext);
        shadowImage.setBackgroundDrawable(SkinManager.getResDrawable(R.drawable.half_circle_line));
        FrameLayout.LayoutParams shadowParams = new FrameLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        shadowParams.topMargin = SkyConstants.Div(33);
        speedLayout.addView(shadowImage, shadowParams);
        initCircle();
        initRightPart();
    }

    private void initCircle() {
        FrameLayout circleLayout = new FrameLayout(mContext);
        FrameLayout.LayoutParams circleParams = new FrameLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL);
        circleParams.leftMargin = SkyConstants.Div(130);
        circleParams.bottomMargin = SkyConstants.Div(3);
        speedLayout.addView(circleLayout, circleParams);

        greenLightImage = new ImageView(mContext);
        greenLightImage.setImageDrawable(SkinManager.getResDrawable(R.drawable.green_light));
        circleLayout.addView(greenLightImage, new FrameLayout.LayoutParams(
                SkyConstants.Div(246), SkyConstants.Div(246), Gravity.CENTER));
        LinearLayout textLayout = new LinearLayout(mContext);
        textLayout.setBackgroundDrawable(SkinManager.getResDrawable(R.drawable.speed_circle_bg));
        textLayout.setOrientation(LinearLayout.VERTICAL);
        textLayout.setGravity(Gravity.CENTER);
        circleLayout.addView(textLayout, new FrameLayout.LayoutParams(
                SkyConstants.Div(246), SkyConstants.Div(246), Gravity.CENTER));

        LinearLayout upTextLayout = new LinearLayout(mContext);
        upTextLayout.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        upTextLayout.setPadding(SkyConstants.Div(18), 0, 0, 0);
        memoryPercentText = newText(numTextSize, mContext.getResources()
                .getColor(R.color.speed_memory_color));
        memoryPercentText.setPadding(0, 0, 0, 0);
        TextView percentText = newText(percentTextSize, mContext.getResources()
                .getColor(R.color.speed_memory_color));
        percentText.setPadding(0, 0, 0, 0);
        percentText.setText("%");
        upTextLayout.addView(memoryPercentText, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        upTextLayout.addView(percentText, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        LinearLayout.LayoutParams upParams = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        textLayout.addView(upTextLayout, upParams);

        TextView memoryTipText = newText(SkyConstants.Dpi(30),
                mContext.getResources().getColor(R.color.defaultColor));
        memoryTipText.setText(R.string.memory_size);
        memoryTipText.setPadding(0, 0, 0, 0);
        LinearLayout.LayoutParams downParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        downParams.topMargin = SkyConstants.Div(-12);
        textLayout.addView(memoryTipText, downParams);
    }

    private void initRightPart() {
        brightColor = mContext.getResources().getColor(R.color.defaultColor);
        darkColor = mContext.getResources().getColor(R.color.disable_color);

        LinearLayout tipLayout = new LinearLayout(mContext);
        tip1Text = newTickText(SkyConstants.Dpi(30), darkColor, R.string.clear_memory);
        tip2Text = newTickText(SkyConstants.Dpi(30), darkColor, R.string.optimalize_system);
        tip3Text = newTickText(SkyConstants.Dpi(30), darkColor, R.string.optimalize_network);

        tip1Image = newImageView();
        tip2Image = newImageView();
        tip3Image = newImageView();
        LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(SkyConstants.Div(50),
                SkyConstants.Div(38));
        imageParams.leftMargin = SkyConstants.Div(30);
        tipLayout.addView(tip1Image, imageParams);
        tipLayout.addView(tip1Text);
        tipLayout.addView(tip2Image, imageParams);
        tipLayout.addView(tip2Text);
        tipLayout.addView(tip3Image, imageParams);
        tipLayout.addView(tip3Text);
        FrameLayout.LayoutParams upParams = new FrameLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                Gravity.LEFT | Gravity.CENTER_VERTICAL);
        upParams.leftMargin = SkyConstants.Div(400);
        upParams.bottomMargin = SkyConstants.Div(51);
        speedLayout.addView(tipLayout, upParams);

        speedingTipText = newText(SkyConstants.Dpi(36),
                mContext.getResources().getColor(R.color.defaultColor));
        speedingTipText.setGravity(Gravity.CENTER);
        speedingTipText.setText(R.string.speeding_up_tip);
        FrameLayout.LayoutParams downParams = new FrameLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
                Gravity.LEFT | Gravity.CENTER_VERTICAL);
        downParams.leftMargin = SkyConstants.Div(402);
        downParams.topMargin = SkyConstants.Div(40);
        downParams.rightMargin = SkyConstants.Div(140);
        speedLayout.addView(speedingTipText, downParams);
    }

    private TextView newText(int textSize, int textColor) {
        TextView text = new TextView(mContext);
        text.setSingleLine();
        text.setTextSize(textSize);
        text.setTextColor(textColor);
        return text;
    }

    private TextView newTickText(int textSize, int textColor, int strId) {
        TextView text = newText(textSize, textColor);
        text.setText(strId);
        //text.setCompoundDrawablesWithIntrinsicBounds(R.drawable.unticked_small, 0, 0, 0);
        //text.setPadding(SkyConstants.Div(25), 0, SkyConstants.Div(5), 0);
        return text;
    }

    private ImageView newImageView() {
        ImageView imageView = new ImageView(mContext);
        imageView.setBackgroundResource(R.drawable.unticked_small);
        imageView.setPadding(SkyConstants.Div(25), 0, SkyConstants.Div(5), 0);
        return imageView;
    }

    public void initStatus() {
        // ??????????? 调用杀进程代码
        speedingTipText.setText(R.string.speeding_up_tip);
        mainHandler.removeCallbacksAndMessages(null);
//        mainHandler.sendEmptyMessageDelayed(START_ANIM, 300);
//        originalPercent = getUsedMemoryPercent();
//        LogUtils.d("speed", "will start speeding up, get used memory = "+originalPercent);
//        crtShowPercent = originalPercent;
//        memoryPercentText.setText(crtShowPercent+"");
//        killProcess();
//        LogUtils.d("speed", "kill finished !!!");
    }

    private void startAnim() {
        if (rotateAnim == null)
            rotateAnim = AnimationUtils.loadAnimation(mContext, R.anim.rotate_clockwise);
        greenLightImage.startAnimation(rotateAnim);

        mainHandler.removeCallbacksAndMessages(null);
        mainHandler.sendEmptyMessage(DOWN);
    }

    private int getUsedMemoryPercent() {
        long freeSize = SystemUtils.getmem_UNUSED(mContext);
        long totalSize = SystemUtils.getmem_TOLAL();
        return (int) (100 - (double) freeSize / (double) totalSize * 100.0f);
    }

    private void killProcess() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    SystemUtils.killAll(mContext);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private final int START_ANIM = 0;
    private final int DOWN = 1;
    private final int UP = 2;
    private final int DISMISS = 3;
    Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case START_ANIM:
                    startAnim();
                    break;
                case DOWN:
                    memoryPercentText.setText(crtShowPercent + "");
                    if (crtShowPercent <= 0) {
                        tip2Text.setTextColor(brightColor);
                        tip2Image.setBackgroundResource(R.drawable.ticked_small);
//                        int afterPercent = getUsedMemoryPercent();
//                        originalPercent = originalPercent > afterPercent ? afterPercent : originalPercent;
//                        LogUtils.d("speed", "anim 0, get used memory = "+originalPercent);
                        mainHandler.sendEmptyMessageDelayed(UP, (int) (speed * 1.5));
                    } else {
                        if (crtShowPercent <= originalPercent / 2) {
                            tip1Image.setBackgroundResource(R.drawable.ticked_small);
                            tip1Text.setTextColor(brightColor);
                        }
                        crtShowPercent--;
                        mainHandler.sendEmptyMessageDelayed(DOWN, speed);
                    }
                    break;
                case UP:
                    memoryPercentText.setText(crtShowPercent + "");
                    if (crtShowPercent >= afterSpeedPercent) {
                        if (rotateAnim != null)
                            rotateAnim.cancel();
                        tip3Image.setBackgroundResource(R.drawable.ticked_small);
                        tip3Text.setTextColor(brightColor);
                        speedingTipText.setText(R.string.speed_up_complete);
                        mainHandler.sendEmptyMessageDelayed(DISMISS, 1000);
                    } else {
                        crtShowPercent++;
                        mainHandler.sendEmptyMessageDelayed(UP, speed);
                    }
                    break;
                case DISMISS:
                    SpeedUpDialog.this.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected void initContentSize() {
        // TODO Auto-generated method stub
        contentWidth = SkyConstants.Div(1158);
        contentHeight = SkyConstants.Div(612);
    }

    public void setInitUsedMemory(int percent) {
        originalPercent = percent;
        mainHandler.sendEmptyMessageDelayed(START_ANIM, 300);
        LogUtils.d("speed", "will start speeding up, init used memory = " + originalPercent);
        crtShowPercent = originalPercent;
        memoryPercentText.setText(crtShowPercent + "");
    }

    private int afterSpeedPercent;

    public void setSpeedUsedMemory(int percent) {
        afterSpeedPercent = percent;
        if (afterSpeedPercent > originalPercent)
            afterSpeedPercent = originalPercent;
        LogUtils.d("speed", "process killed, after speed used memory = " + percent);
    }
}
